package cdu.zch.healthcare;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

public class AppointmentRecordActivity extends AppCompatActivity {

    ListView listView;
    Button buttonBack;
    ArrayList<String[]> orderList = new ArrayList<>();
    //ArrayAdapter<String> adapter;
    Database db;
    SimpleAdapter sa;
    ArrayList<HashMap<String, String>> list;
    private static final int REQUEST_SCHEDULE_EXACT_ALARM = 1;

    AppointmentAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointment_record);

        listView = findViewById(R.id.listViewOD);
        buttonBack = findViewById(R.id.buttonODBack);

        db = new Database(getApplicationContext(), "healthcare", null, 3);

        // 检查并请求权限
        checkAndRequestExactAlarmPermission();

        // 获取当前日期
        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        list = new ArrayList<>();
        // 格式化时间
        Calendar calendar = Calendar.getInstance();
        // 设置时区
        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai"); // 根
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        timeFormat.setTimeZone(timeZone); // 设置时区
        String currentTime = timeFormat.format(calendar.getTime());

        // 从数据库中检索数据
        ArrayList<String[]> data = db.getAppointmentsAfterDate(currentDate,currentTime);
        for (String[] appointment : data) {
            HashMap<String, String> item = new HashMap<>();
            item.put("line1", appointment[0]);
            item.put("line2", appointment[1] + " " + appointment[2]);
            list.add(item);
        }
//        orderList.addAll(data);
//        sa = new SimpleAdapter(this,
//                list,
//                R.layout.multi_lines_appointment,
//                new String[]{"line1", "line2"},
//                new int[]{R.id.name, R.id.time}
//        );
//        sa.setViewBinder(new SimpleAdapter.ViewBinder() {
//            @Override
//            public boolean setViewValue(View view, Object data, String textRepresentation) {
//                if (view.getId() == R.id.cancel) {
//                    Button cancelButton = (Button) view;
//                    cancelButton.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            // 处理取消按钮点击事件，例如弹出确认对话框或直接处理取消逻辑
//                            // 注意：这里的逻辑应根据实际需求来实现
//                            int position = (int) v.getTag(); // 获取按钮所在列表项的位置
//                            String[] order = orderList.get(position);
//                            db.cancelAppointment(order[0], order[1]);
//                            orderList.remove(position);
//                            list.remove(position);
//                            notifyDataSetChanged(); // 通知适配器数据变化
//                            Toast.makeText(getApplicationContext(), "预约已取消", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                    return true;
//                }
//                return false;
//            }
//        });
//        listView.setAdapter(sa);
        adapter = new AppointmentAdapter(this, list, db);
        listView.setAdapter(adapter);

        // 返回按钮
        buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AppointmentRecordActivity.this, HomeActivity.class));
            }
        });

        // 取消预约功能
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//                new AlertDialog.Builder(AppointmentRecordActivity.this)
//                        .setTitle("取消预约")
//                        .setMessage("确定要取消这个预约吗？")
//                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                String[] order = orderList.get(position);
//                                db.cancelAppointment(order[0], order[1]);
//                                orderList.remove(position);
//                                list.remove(position);
//                                adapter.notifyDataSetChanged();
//                                Toast.makeText(getApplicationContext(), "预约已取消", Toast.LENGTH_SHORT).show();
//                            }
//                        })
//                        .setNegativeButton("否", null)
//                        .show();
//            }
//        });


        // 提醒用户
        checkForReminders();
    }

    private void checkAndRequestExactAlarmPermission() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null && !alarmManager.canScheduleExactAlarms()) {
            // 请求权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.SCHEDULE_EXACT_ALARM)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.SCHEDULE_EXACT_ALARM},
                        REQUEST_SCHEDULE_EXACT_ALARM);
            } else {
                // 引导用户到设置中授予权限
                Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_SCHEDULE_EXACT_ALARM) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授予后执行的代码
            } else {
                // 权限被拒绝后的处理
            }
        }
    }

    private void checkForReminders() {
        // 获取当前日期的 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        // 将日期加上一天，即获取明天的日期
//        calendar.add(Calendar.DAY_OF_YEAR, 1);
        // 格式化明天的日期为 "yyyy-MM-dd" 格式的字符串
        String tomorrowDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai"); // 根
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        timeFormat.setTimeZone(timeZone); // 设置时区
        String currentTime = timeFormat.format(calendar.getTime());
        ArrayList<String[]> reminders = db.getAppointmentsForDate(tomorrowDate,currentTime);
        // 遍历每个预约记录
        for (String[] reminder : reminders) {
            String reminderDetails = "预约: " + reminder[1] + " 时间: " + reminder[5] + " " + reminder[6];
            scheduleNotification(reminderDetails, reminder[5], reminder[6]);
        }

    }

    private void scheduleNotification(String content, String date, String time) {
        Intent intent = new Intent(this, ReminderBroadcastReceiver.class);
        intent.putExtra("reminder", content);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date dateTime = dateFormat.parse(date + " " + time);
            calendar.setTime(dateTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (alarmManager != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                } else {
                    alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
            // 处理 SecurityException
            checkAndRequestExactAlarmPermission();
        }
    }
}
